var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

//引入路由
var indexRouter = require('./routes/index');
var adminRouter = require('./routes/admin');

var app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*'); 
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Methods', '*');
  res.header('Content-Type', 'application/json;charset=utf-8');
  next();
});

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//挂载路由
app.use(indexRouter);

// app.use((req, res, next) => {
//   // 如果不是登录页面 并且没有登录则跳转登录页面 ,否则放行
//   if (req.originalUrl != '/admin/login' && !req.session.user) {
//       res.redirect('/admin/login');
//   }
//   next();
// });

app.use('/admin', adminRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) { 
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};  
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
